package com.jackrain.clouddata.oms.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.aliyun.openservices.ons.api.Message;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class RetPurDao {
    private static final Logger logger = LoggerFactory.getLogger(RetPurDao.class);

    @Transactional
    public void insert(JSONObject paramObject,String tag) throws SQLException {
        logger.info("==================调用dao=================");
        /* paramObject格式
         *{
         * "name":"xxx",
         * "value":"xxx",
         * "item":[{"name":"xxx","value":[{xxx},{xxx}]}]
         * }
         */
        String tableName = paramObject.getString("name");
        JSONObject valueJson = paramObject.getJSONObject("value");
        JSONArray items = paramObject.getJSONArray("item");

        Integer ad_client_id = QueryEngine.getInstance().doQueryInt("SELECT AD_CLIENT_ID FROM OMS_TAG WHERE TAGNAME = ?", new Object[]{tag});
        if (null == ad_client_id || "".equals(ad_client_id)) {
            throw new NDSException("公司ID未找到!");
        }
        // 插入主表去重
        String selSql = "SELECT COUNT(1) FROM "+tableName+" WHERE BILLNO = ? AND AD_CLIENT_ID = ?";
        int count = QueryEngine.getInstance().doQueryInt(selSql, new Object[]{valueJson.get("BILLNO"),ad_client_id});
        if (count > 0){
        }else{
            StringBuffer strBuf = new StringBuffer("INSERT INTO " + tableName + "(");
            List paramList = new ArrayList();
            Set<String> keySet = valueJson.keySet();
            for (String key: keySet) {
                strBuf.append(key + ",");
                if (key.substring(key.length() - 4, key.length()).equals("DATE")) {
                    paramList.add(TypeUtils.castToDate(valueJson.get(key)));
                } else if (null == valueJson.get(key) || "".equals(valueJson.get(key))) {
                    paramList.add("");
                } else {
                    paramList.add(valueJson.get(key));
                }
            }
            strBuf.append("ID,AD_CLIENT_ID) VALUES(");
            for (int j = 0; j < keySet.size(); j++) {
                strBuf.append("?,");
            }
            strBuf.append("?,?)");
            paramList.add(Tools.getSequence(tableName));
            paramList.add(ad_client_id);
            QueryEngine.getInstance().executeUpdate(strBuf.toString(),paramList.toArray());

            for (int i = 0; i < items.size(); i++) {
                String itemTableName = paramObject.getJSONArray("item").getJSONObject(i).getString("name");
                JSONArray itemValues = paramObject.getJSONArray("item").getJSONObject(i).getJSONArray("value");
                // 插入子表
                for (int j = 0; j < itemValues.size(); j++) {
                    StringBuffer strItemBuf = new StringBuffer("INSERT INTO " + itemTableName + "(");
                    paramList = new ArrayList();
                    Set<String> itemKeySet = itemValues.getJSONObject(j).keySet();
                    for (String key : itemKeySet) {
                        strItemBuf.append(key + ",");
                        if (key.substring(key.length() - 4, key.length()).equals("DATE")) {
                            paramList.add(TypeUtils.castToDate(itemValues.getJSONObject(j).get(key)));
                        } else if (null == itemValues.getJSONObject(j).get(key) || "".equals(itemValues.getJSONObject(j).get(key))) {
                            paramList.add("");
                        } else {
                            paramList.add(itemValues.getJSONObject(j).get(key));
                        }
                    }
                    strItemBuf.append("ID,AD_CLIENT_ID) VALUES(");
                    for (int k = 0; k < itemKeySet.size(); k++) {
                        strItemBuf.append("?,");
                    }
                    strItemBuf.append("?,?)");
                    paramList.add(Tools.getSequence(itemTableName));
                    paramList.add(ad_client_id);
                    QueryEngine.getInstance().executeUpdate(strItemBuf.toString(), paramList.toArray());
                }
            }
        }
    }
}
